package com.rent.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rent.model.JsCode2SessionModel;
import com.rent.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 和微信交互的封装了
 */
@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {
    private static final String jscode2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public JsCode2SessionModel getWechatMsgByCode(String code, String appid, String secret) {
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(jscode2sessionUrl);
        urlBuilder.append("?appid=" + appid);
        urlBuilder.append("&secret=" + secret);//自己的appSecret
        urlBuilder.append("&js_code=" + code);
        urlBuilder.append("&grant_type=authorization_code");
        urlBuilder.append("&connect_redirect=1");
        HttpRequest httpRequest = HttpRequest.get(urlBuilder.toString());
        HttpResponse execute = httpRequest.execute();
        String body = execute.body();
        JsCode2SessionModel jsCode2SessionModel = JSONUtil.toBean(body, JsCode2SessionModel.class);
        log.info("call weixin api ,getWechatMsgByCode: [{}]", JSONObject.toJSONString(jsCode2SessionModel));
        return jsCode2SessionModel;
    }
}
